<?php
/**
 * Created by PhpStorm.
 * User: sheldon
 * Date: 18-1-22
 * Time: 下午1:55
 */

$users = json_decode(file_get_contents('data/users.json'), true);
$prizes = json_decode(file_get_contents('data/prizes.json'), true);
$winners = json_decode(file_get_contents('data/winners.json'), true);
$ignores = json_decode(file_get_contents('data/ignore.json'), true);

function getPrizeNameById($prizes, $id) {
    if (!empty($prizes)) {
        foreach ($prizes as $index => $prize) {
            if ($prize['id'] == $id) {
                return $prize['name'];
            }
        }
    }
    return "";
}

function userNotExist($users, $name) {
    if (!empty($users)) {
        foreach ($users as $index => $user) {
            if ($user == $name) {
                return false;
            }
        }
    }
    return true;
}

/**
 * 根据范围取范围内随机数
 * @param $max
 * @return int
 */
function my_random($max) {
    if ($max < 2) {
        return 1;
    }
    return getRandom(1, $max);
    $url = "https://www.random.org/integers/?num=1&min=1&max={$max}&col=1&base=10&format=plain&rnd=new";
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_HEADER, 1);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
    $data = curl_exec($curl);
    curl_close($curl);
    list($header, $body) = explode("\r\n\r\n", $data, 2);
    preg_match_all("/HTTP\/1\.1 ([\d]{3})/", $header, $matches);
    if (isset($matches[1][0]) && $matches[1][0] == 200) {
        return $body;
    } else {
        return getRandom(1, $max);
    }
}

/**
 * 调用系统 /dev/urandom 获取随机数
 * @param int $min
 * @param int $max
 * @return int
 */
function getRandom($min = 0, $max = 0x7FFFFFFF)
{
    $diff = $max - $min;
    if ($diff > PHP_INT_MAX) {
        throw new RuntimeException('Bad Range');
    }

    $fh = fopen('/dev/urandom', 'r');
    stream_set_read_buffer($fh, PHP_INT_SIZE);
    $bytes = fread($fh, PHP_INT_SIZE );
    if ($bytes === false || strlen($bytes) != PHP_INT_SIZE ) {
        //throw new RuntimeException("nable to get". PHP_INT_SIZE . "bytes");
        return 0;
    }
    fclose($fh);

    if (PHP_INT_SIZE == 8) { // 64-bit versions
        list($higher, $lower) = array_values(unpack('N2', $bytes));
        $value = $higher << 32 | $lower;
    }
    else { // 32-bit versions
        list($value) = array_values(unpack('Nint', $bytes));

    }

    $val = $value & PHP_INT_MAX;
    $fp = (float)$val / PHP_INT_MAX; // convert to [0,1]

    return (int)(round($fp * $diff) + $min);
}


$error = $success = $warning = "";
